﻿using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Red.Toolkit.HoudiniDispatch
{
    /// <summary>
    /// Message Struct for Incoming Messages
    /// </summary>
    public struct Received
    {
        public IPEndPoint Sender;
        public string Message;
    }


    /// <summary>
    /// Base class for UDP Comm
    /// </summary>
    abstract class UdpBase
    {
        protected UdpClient Client;

        #region C-tor
        protected UdpBase()
        {
            Client = new UdpClient();
        }
        #endregion  C-tor

        #region Public Methods
        public async Task<Received> Receive()
        {
            var result = await Client.ReceiveAsync();
            return new Received()
            {
                Message = Encoding.ASCII.GetString( result.Buffer, 0, result.Buffer.Length ),
                Sender = result.RemoteEndPoint
            };
        }
        #endregion Public Methods
    }

    /// <summary>
    /// UDP Listener Class
    /// </summary>
    class UdpUser : UdpBase
    {
        #region Data
        private UdpUser() { }
        private static string _serverIP;
        private static int _port;
        #endregion Data

        #region C-Tor
        public static UdpUser ConnectTo( string hostname, int port )
        {
            var connection = new UdpUser();
            connection.Client.Connect( hostname, port );
            return connection;
        }
        #endregion  C-Tor

        #region Public Methods
        public static UdpUser Connect()
        {
            var connection = new UdpUser();

            //Read client config file and get Server IP and Port
            System.IO.StreamReader configReader = new System.IO.StreamReader( @"Data\clientconfig.txt" );

            string line = "";
            while ( (line = configReader.ReadLine()) != null )
            {
                string[] lineSplit = line.Split( '|' );
                if ( "server_ip" == lineSplit[0] )
                    _serverIP = lineSplit[1];
                if ( "port" == lineSplit[0] )
                    int.TryParse(lineSplit[1], out _port);
            }
            connection.Client.Connect( _serverIP, _port );

            return connection;
        }

        public void Send( string message )
        {
            var datagram = Encoding.ASCII.GetBytes( message );
            Client.Send( datagram, datagram.Length );
        }
        #endregion Public Methods
    }
}
